package rhelper

import (
	"fmt"
	"github.com/garyburd/redigo/redis"
	"log"
	"strconv"
	"strings"
)

//var UpdateFlag = make(map[string](chan int))
var Subscriptions = map[string][]chan int{}

var UpdateFlag = make(chan string)

func init() {

}

//subscriptions := map[][chan string]chan string{
//pub1: []chan string{sub1, sub2},
//pub2: []chan string{sub2, sub3},
//}

func isControllerOnline(serverId string, cid string) bool {
	if serverId == "" {
		return false
	}

	if cid == "" {
		return false
	}

	rconn := Pool().Get()
	defer rconn.Close()
	exist, err := redis.Int(rconn.Do("SISMEMBER", OnlineDev, ControllerHash+cid))
	if err != nil {
		log.Println("isControllerOnline err:", err)
	}

	if exist != 1 {
		return false
	}

	return true
}

func GetControllerOnlineStatus(serverId string, cid string) string {
	if isControllerOnline(serverId, cid) {
		return "on"
	}

	return "off"
}

func CommaString2Array(src string) []string {
	if src == "" {
		return []string{}
	}

	var result []string
	if strings.Contains(src, ",") {
		result = strings.Split(src, ",")
	} else {
		result = []string{src}
	}

	return result
}

func SplitString2Array(src string, splitchar string) []string {
	if src == "" {
		return []string{}
	}

	var result []string
	if strings.Contains(src, splitchar) {
		result = strings.Split(src, splitchar)
	} else {
		result = []string{src}
	}

	return result
}

func CommaStringContain(src string, substr string) bool {
	result := CommaString2Array(src)
	for _, a := range result {
		if a == substr {
			return true
		}
	}
	return false
}

func CommaStringAppend(src string, appendx string) string {
	if src == "" {
		return appendx
	}

	if CommaStringContain(src, appendx) {
		return src
	}

	return src + "," + appendx
}

func CommaReportAppend(src string, currentTime string, e string, t string) string {
	inte, err := strconv.ParseUint(e, 16, 32)
	if err != nil {
		panic(err)
	}

	intt, err := strconv.ParseUint(t, 16, 32)
	if err != nil {
		panic(err)
	}

	if src == "" {
		return fmt.Sprintf("%s:%d:%d", currentTime, inte, intt)
	}

	s := strings.Split(src, ":")
	lastTime := s[0]

	if currentTime != lastTime {
		return fmt.Sprintf("%s:%d:%d", currentTime, inte, intt)
	}

	stre := s[1]
	strt := s[2]

	srce, _ := strconv.ParseUint(stre, 10, 32)
	inte = inte + srce

	srct, _ := strconv.ParseUint(strt, 10, 32)
	intt = intt + srct

	return fmt.Sprintf("%s:%d:%d", currentTime, inte, intt)

}

func CommaStringDelete(src string, appendx string) string {
	if src == "" {
		return ""
	}

	strArray := CommaString2Array(src)
	for index, element := range strArray {
		if element == appendx {
			strArray = append(strArray[:index], strArray[index+1:]...)
			break
		}
	}

	str := ""
	for _, element := range strArray {
		str = str + element + ","
	}

	strSize := len(str)
	if strSize > 0 && str[strSize-1] == ',' {
		str = str[:strSize-1]
	}
	return str
}
